package com.sendi.common.service;

import java.util.List;

import com.sendi.common.dao.CommonDaoHibernate;
import com.sendi.common.util.Page;
import com.sendi.common.util.QueryRule;

public class ServiceSupport implements Service {
	
	private CommonDaoHibernate dao;
	protected Class entityClass;

	public CommonDaoHibernate getDao() {
		return dao;
	}

	public void setDao(CommonDaoHibernate dao) {
		this.dao = dao;
	}

	public Class getEntityClass() {
		return entityClass;
	}

	public void setEntityClass(Class entityClass) {
		this.entityClass = entityClass;
	}

	public Object delete(Object obj) {
		dao.delete(obj);
		return obj;
	}

	public boolean exists(Object obj) {
		return dao.contains(obj);
	}

	public Page findByHql(final String hql,final int startIndex,final int pageSize,Object[] values){
		return dao.findByHql(hql,startIndex,pageSize,values);
	}
	public List findByHql(String hql, Object[] values) {
		return dao.findByHql(hql, values);
	}

	public Page getPageByHql(String hql, int startIndex, int pageSize,
			Object[] values) {
		return dao.findByHql(hql, startIndex, pageSize, values);
	}

	public List findByProperty(String propertyName, Object value) {
		QueryRule qr = QueryRule.getInstance();
		qr.addEqual(propertyName, value);
		return dao.find(getEntityClass(), qr);
	}

	public Object get(Long id) {
		return dao.get(entityClass, id);
	}

	public Object getUnique(Long id) {
		return dao.get(entityClass, id);
	}

	public Object getUnique(String propertyName, Object value) {
		return dao.getUnique(getEntityClass(), propertyName, value);
	}
	
	public Object getUnique(QueryRule queryRule) {
		return dao.getUnique(getEntityClass(),queryRule);
	}

	public Object save(Object obj) {
		validate(obj);
		dao.save(obj);
		doLog(obj);
		return obj;
	}

	public Object update(Object obj) {
		validate(obj);
		dao.update(obj);
		doLog(obj);
		return obj;
	}
	
	protected void validate(Object obj){
		// implement by subclass
	}
	
	protected void doLog(Object obj){
		
	}

}
